package net.mcfire.aliyunplugin;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Consumer;

public class WeaponLoader {

    /**
     * Get weapon storage.
     * @param username
     * @return Map: Category Tag => Weapon Tag (weapon:magazine)
     * @throws HTTP.APIException
     */
    public static Map<String, String> get(String username) throws HTTP.APIException {
        JSONObject params = new JSONObject();
        params.put("u", username);

        JSONArray w = HTTP.api("/storage/weapons", params).getJSONObject("data").getJSONArray("weapons");
        Map<String, String> ret = new HashMap<>();
        for(int i = 0; i < w.size(); i++) {
            final JSONObject tags = w.getJSONObject(i);
            final String k = tags.getString("cat_tag");
            final String val = tags.getString("item_tag");
            ret.put(k, val);
        }

        return Collections.unmodifiableMap(ret);
    }

    /**
     * Queue an asynchronous task
     * @param username
     * @param handler
     */
    public static void load(String username, Consumer<Map<String, String>> handler) {
        AliyunPlugin.task(new WeaponLoaderTask(username, handler));
    }

    public static class WeaponLoaderTask implements Runnable {

        private final String username;

        private final Consumer<Map<String, String>> handler;

        private Map<String, String> result = null;

        public WeaponLoaderTask(String username, Consumer<Map<String, String>> handler) {
            this.username = username;
            this.handler = handler;
        }

        @Override
        public void run() {
            int trials = 0;
            while(result == null && trials < 3) {
                tryLoad();
                if(result == null) {
                    try {
                        Thread.sleep(1000L);
                    } catch (InterruptedException e) {
                    }
                }
                trials ++;
            }
            handler.accept(result);
        }

        private void tryLoad() {
            try {
                result = get(username);
            } catch (Exception ex) {
                ex.printStackTrace();
                AliyunPlugin.plugin.getLogger().severe(String.format("Weapon load failed<%s>: %s", ex.getClass().getSimpleName(), ex.getMessage()));
            }
        }
    }

}
